package com.example.zjx8969.myapplication;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.transition.Slide;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.example.zjx8969.myapplication.anotation.PageMark;
import com.example.zjx8969.myapplication.cache.StorageType;
import com.example.zjx8969.myapplication.compare.ControlExtra;
import com.example.zjx8969.myapplication.compare.SDKInfo;
import com.example.zjx8969.myapplication.database.Book;
import com.example.zjx8969.myapplication.database.DataBaseHolder;
import com.example.zjx8969.myapplication.database.User;
import com.example.zjx8969.myapplication.jobscheduler.JobSchedulerService;
import com.example.zjx8969.myapplication.net.InitBean;
import com.example.zjx8969.myapplication.viewmodel.InitalViewModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import cn.qqtheme.framework.picker.TimePicker;
import hawk.sit.threads.RunnablePriority;


@PageMark(path = "om.example.zjx8969.myapplication.MainActivity", extras = 1 << 1)
public class MainActivity extends BaseActivity {
    NotificationView notificationView;
    boolean status;
    WeakReference<String> mReferece;
    String vId = "jGmrobJyKtE";//3rkIXIFV8jA,
    ImageView imageView;
    TextView textView;
    InitalViewModel initalViewModel;
    private String TAG = "tag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        getWindow().setEnterTransition(new Slide(Gravity.END));
/*        AppModule appModule = new AppModule();
        List<Class<? extends RegisterInterface>> interfaces = new ArrayList<>(4);
        appModule.loadInto(interfaces);
        for (Class clazz : interfaces) {
            try {
                Object o = clazz.newInstance();
                ((RegisterInterface) o).register();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }*/
        textView = (TextView) findViewById(R.id.txt_show);
        hawk.sit.threads.Logger.setDebug(true);
        String url = "http://f.yhres.com/share_webcastEKZmAQL3BQp0ZQMinSx/2017/04/14/513855494010457_3.png-q75";

        Glide.with(this).load(url).submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

        notificationView = (NotificationView) findViewById(R.id.notification_background);
        imageView = (ImageView) findViewById(R.id.image);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int systemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            getWindow().getDecorView().setSystemUiVisibility(systemUiVisibility | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        initalViewModel = new ViewModelProvider(this).get(InitalViewModel.class);
        initalViewModel.getData().observe(this, new Observer<InitBean>() {
            @Override
            public void onChanged(@Nullable InitBean initBean) {
                if (initBean != null) {
                    Log.e("tag", initBean.defaultSite + " " + Thread.currentThread().getName());
                } else {
                    Log.e("tag", "bean is null " + Thread.currentThread().getName());
                }
            }
        });


        mReferece = new WeakReference<String>("hello");


//        WebView webView = findViewById(R.id.web);
//        webView.loadUrl("https://www.youtube.com/watch?v=pxSmO5-CtyI");


//        YouTubePlayerFragment fragment = new YouTubePlayerFragWrapper();
//        fragment.initialize(vId, new YouTubePlayer.OnInitializedListener() {
//            @Override
//            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
//                Log.e("tag", "onInitializationSuccess " + b);
//                youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
//                youTubePlayer.loadVideo(vId);
//            }
//
//            @Override
//            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//                Log.e("tag", "onInitializationFailure ");
//            }
//        });
//        getFragmentManager().beginTransaction().add(R.id.container, fragment, "s").commit();

//        findViewById(R.id.container).addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                if (right == oldRight && bottom == oldBottom) {
//                    Log.e("tqag", "onLayoutChange " + v.getId()+","+(v.getVisibility()==View.VISIBLE));
//
//                }
//            }
//        });
//        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
//        webView.loadUrl("https://www.youtube.com/watch?v=MChPrGnUW7Y");

        Log.e("tag", "MainActivity>" + Thread.currentThread().getName() + " execute");


    }


    public void onDrawableRightClick(View view) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_APP_EMAIL);
        startActivity(intent);
        startActivity(Intent.createChooser(intent, ""));
        if (initalViewModel != null) {
            initalViewModel.changeData();
        }
        Log.e("tag", "max:" + (1 << 31));
        boolean hasMark = getClass().isAnnotationPresent(PageMark.class);
        if (!hasMark) return;
        PageMark annotation = getClass().getAnnotation(PageMark.class);
        Log.e("tag", annotation.path() + " " + annotation.extras());


/*        Log.e("tag", "getExternalCacheDir>" + StorageType.cache.getStorageLocation(this).getAbsolutePath());
        Log.e("tag", "getExternalFilesDir>" + StorageType.file.getStorageLocation(this).getAbsolutePath());
        Log.e("tag", "getInnerFilesDir>" + StorageType.innerFile.getStorageLocation(this).getAbsolutePath());
        Log.e("tag", "getInnerCacheDir>" + StorageType.innerCache.getStorageLocation(this).getAbsolutePath());*/


        Drawable[] compoundDrawables = textView.getCompoundDrawables();
        textView.setText("hello " + Math.random());
        textView.setCompoundDrawablePadding(10);
        if (compoundDrawables[2] == null) {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_person_info_email_warning);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(null, null, drawable, null);
        } else {
            textView.setCompoundDrawables(null, null, null, null);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void onExplorerClicked(View view) {
        Book book = new Book();
        book.bookId = 102;
        book.title = "pragroming";
        book.userId = "1";

        long t1 = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            to64StringSimple(System.nanoTime());
        }
        System.out.println("to64String spend  " + (System.nanoTime() - t1));
        t1 = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            to62String(System.nanoTime());
        }

        System.out.println("to62String spend  " + (System.nanoTime() - t1));

        int measuredWidth = view.getMeasuredWidth();
//        AnimatorSet animatorSetLeftFadeIn = new AnimatorSet();
//        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "translationX", getResources().getDisplayMetrics().widthPixels, view.getLeft());
//        ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1.0f);
//        animatorSetLeftFadeIn.setDuration(1000).play(objectAnimator).with(alpha);
//        animatorSetLeftFadeIn.start();
//        objectAnimator.setDuration(3000);
//        objectAnimator.start();
//        startActivity(new Intent(this, FirstEntranceExplorerAnimationActivity.class));
    }

    public static String to62String(long args) {
        long rest = args;
        StringBuilder stringBuffer = new StringBuilder();
        while (rest != 0) {
            Character character = charSet[(int) (rest % 62)];
            stringBuffer.append(character);
            rest = rest / 62;
        }
        return stringBuffer.reverse().toString();
    }

    public static String to64StringSimple(long args) {
        long rest = args;
        StringBuilder stringBuffer = new StringBuilder();
        while (rest != 0) {
            Character character = charSet[(int) (rest & 0x3F)];
            stringBuffer.append(character);
            rest = rest >> 6;
        }
        return stringBuffer.reverse().toString();
    }

    public void onRxJavaClicked(View view) {
        startActivity(new Intent(this, RxJavaActivity.class));

    }


    public void onUriParasClicked(View view) {


/*        File imagePath = new File(Environment.getExternalStorageDirectory(), "Pictures/NewTextFile.txt");//new File(getFilesDir(), "images");
//        File newFile = new File(imagePath, "default_image.jpg");
        Uri contentUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imagePath);
        Log.e("tag", contentUri.toString());*/

//        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "Download/app-preview-release.apk"));
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(uri, "application/vnd.android.package-archive");
//        startActivity(intent);
//        Log.e("tag", uri.getAuthority());
    }

    public void getCache(StorageType type) {
        Log.e("tag", type.getStorageLocation(this).getAbsolutePath());
    }

    public void onChangeClicked(View view) {
        Intent intent = new Intent("P365Launch://invite?code=4BDE6F5C&package=I10020160930");
        startActivity(intent);

//        String url = "http://img3.3lian.com/2006/013/08/20051103121023912.gif";

//        String url = "http://f.yhres.com/wm/share_webcastEKZkAmtlAwDkZwuinSx/2017/12/27/536033683966352_0@r_1800w_1012h.jpg-q75";//宽图
        String url = "http://f.yhres.com/share_webcastEKZmAQL3BQp0ZQMinSx/2017/04/14/513855494010457_3.png-q75";//1:1正好
//        Glide.with(this).asBitmap().load(url).into(imageView);
//        String url = "http://img.hb.aicdn.com/7732412564343cd1f8a1dadc9c63ce12a7a984c739f79-eM76x5_fw658";

/*        String requestUrl = "http://api.yhouse.com/config/init";
        OkHttpUtils.get().url(requestUrl).build().execute(new NetCallBackWrapper<InitBean>() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(final InitBean response, int id) {
                CacheFileManager cacheFileManager = CacheFileManager.getInstance();
                cacheFileManager.writeContentInThread(vId, response);
                Log.e("Tag", "onResponse: " + response.version);
                String key = response.scheme.firstKey();
                Log.e("Tag", "onResponse: " + key + "=" + response.scheme.get(key));
            }
        });*/

//        }
        notificationView.change(status);
        status = !status;
    }

    public String fileKey = "config/init";

    public void onPendingTextClicked(View view) {
        TimePicker timePicker = new TimePicker(this);
//        timePicker.setOffset(5);
        timePicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                showToast(hour + ":" + minute);
            }
        });

        timePicker.show();
//        notificationView.appendText("appendText:" + SystemClock.uptimeMillis());
    }


    Toast toast;

    public synchronized void showToast(String content) {
        if (toast == null) {
            toast = Toast.makeText(this, content, Toast.LENGTH_LONG);
        } else {
            toast.setText(content);
        }
        toast.show();
    }

    public void onCheckDateTimeClicked(View view) {

        Toast.makeText(this, getString(R.string.chat_artist_recall_message, getTopActivityName(this)), Toast.LENGTH_SHORT).show();

    }


    public static String getTopActivityName(Context context) {
        ActivityManager systemService = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = systemService.getRunningTasks(1);
        if (runningTasks == null || runningTasks.size() == 0) return null;
        return runningTasks.get(0).topActivity.getClassName();
    }


    public void onRunThreadPoolClicked(View view) {
        for (int i = 0; i < 20; i++) {
            RunnablePriority priority = i % 5 == 0 ? RunnablePriority.HIGH : RunnablePriority.LOW;
            hawk.sit.threads.PriorityThreadPool.getInstance().execute(priority, new PriorityThread(i));
        }
    }

    public void onStartServiceAndJumpClicked(View view) {
        getInstalledApp(this);
        InetAddress ia = null;
        try {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager.isWifiEnabled()) {
                int ip = wifiManager.getConnectionInfo().getIpAddress();
                String ipStr = intToIp(ip);
                Log.d(TAG, "onStartServiceAndJumpClicked: " + ipStr + "," + wifiManager.getConnectionInfo().getBSSID());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

     /*   HelloServices navigation = (HelloServices) ARouter.getInstance().build("/group/hello").navigation();
        navigation.sayHello();*/
    }

    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }

    public static String getInstalledApp(Context context) {
        PackageManager packageManager = context.getPackageManager();
        List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
        StringBuilder stringBuilder = new StringBuilder(200);
        for (ApplicationInfo applicationInfo : installedApplications) {
//            Log.d("app", applicationInfo.loadLabel(packageManager) + ":" + applicationInfo.packageName);
            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                Log.e("tag", applicationInfo.loadLabel(packageManager) + "_" + applicationInfo.packageName);
//                stringBuilder.append(applicationInfo.loadLabel(packageManager)).append(",");
            }
        }
        if (stringBuilder.length() > 1) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        return stringBuilder.toString();
    }

    public void onYoutubePlayClick(View view) {

        /*startActivity(new Intent(this, YoutubeFragmentActivity.class));*/
    }

    public void onInsertDBClick(View view) {
        String hostUrl = "https://stgexpsvr.perfect365.com/perfect365/perfect365/services";

        User user = new User();
        user.uid = "EKZmZGVmZwH4ZmyinSx";
        user.name = "董大牙";
        user.avatar = "http://f.yhres.com/userAvatar/2017/08/05/EKZ0AwNmAmZ3ZmyinSx_Q3ueOTJu.jpg-ssq75";

        User user2 = new User();
        user2.uid = "EKZmZGVmZwH4ZmyinSx2";
        user2.name = "董大牙2";
        user2.avatar = "http://f.yhres.com/userAvatar/2017/08/05/EKZ0AwNmAmZ3ZmyinSx_Q3ueOTJu.jpg-ssq75";
        DataBaseHolder.getInstance().database.userDao().insert(user2);
        DataBaseHolder.getInstance().database.userDao().insert(user);

        Book book1 = new Book();
        book1.bookId = 1;
        book1.title = "和平";
        book1.userId = user.uid;
        DataBaseHolder.getInstance().database.bookDao().insert(book1);
        Book book2 = new Book();
        book2.bookId = 2;
        book2.title = "战争";
        book2.userId = user2.uid;
        DataBaseHolder.getInstance().database.bookDao().insert(book2);


        Book book12 = new Book();
        book12.bookId = 3;
        book12.title = "玫瑰";
        book12.userId = user2.uid;
        DataBaseHolder.getInstance().database.bookDao().insert(book12);

    }

    public void onReadDBClick(View view) {

        List<User> users = DataBaseHolder.getInstance().database.userDao().getAll();
        if (users != null) {
            for (User user : users) {
                Log.e("tag", user.toString());
            }
        }
        String[] query = new String[]{"1", "3"};
        List<Book> books = DataBaseHolder.getInstance().database.bookDao().query(query);
        if (books != null) {
            for (Book user : books) {
                Log.e("tag", user.toString());
            }
        }
        //测试级联操作
        /* DataBaseHolder.getInstance().database.userDao().delete("EKZmZGVmZwH4ZmyinSx2");*/
    }

    public void onChromeTabClicked(View view) {

        String url = "https://m.yhouse.com/share-guide-app/1462783";
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.launchUrl(this, Uri.parse(url));
    }

    public void onInjectClicked(View view) {
        DataBaseHolder.getInstance().localRelativeDatabase.sdkInfoDao().setCrash("unifyid", "i'm crash info");
        String url = "http://f.yhres.com/wm/share_webcastEKZ4BGN2AQD2AJ9bJD/2017/02/08/508252090546562_0.png-q75";
        if (url.endsWith("-q75")) {
            url = url.substring(0, url.length() - 4);
        }
        String waterMarkPath = "/wm/";
        if (url.contains(waterMarkPath)) {
            int index = url.indexOf(waterMarkPath);
            url = new StringBuffer(url.length()).append(url.substring(0, index + 1))
                    .append(url.substring(index + waterMarkPath.length(), url.length())).toString();
        }

        String fileName = url.substring(url.lastIndexOf("/") + 1);
        String extension = fileName.substring(fileName.lastIndexOf("."));
        if (TextUtils.isEmpty(extension)) {
            fileName += ".jpg";
        }
        Log.d("tag", url);
        Log.d("tag", fileName);

        /*startActivity(new Intent(this, InjectActivity.class));*/

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onJobServiceClicked(View view) {
        JobScheduler systemService = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

        List<JobInfo> allPendingJobs = systemService.getAllPendingJobs();
        for (JobInfo jobInfo : allPendingJobs) {
            if (jobInfo.getId() == 1) {
//                systemService.cancel(1);
                Log.e("tag", "job registered");
                return;
            }
        }

        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(this, JobSchedulerService.class))
                .setRequiresDeviceIdle(false)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.setPeriodic(TimeUnit.MINUTES.toMillis(15), JobInfo.getMinFlexMillis());
        } else {
            builder.setMinimumLatency(TimeUnit.MINUTES.toMillis(5));
        }


        int jobStatus = systemService.schedule(builder.build());
        Log.e("tag", "jobStatus:" + jobStatus);
    }

    public void onCompareClicked(View view) {
        SDKInfo unifyid = DataBaseHolder.getInstance().localRelativeDatabase.sdkInfoDao().find("unifyid");
        if (unifyid != null) {
            Log.e("tag", unifyid.toString());
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            return;
        }

    }

    public void onCompareSmallClicked(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            return;
        }
    }

    public void onComplexWriteClicked(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            return;
        }


    }


    public void onComplexReadClicked(View view) {
        Intent intent = new Intent("P365Launch://invite?code=4BDE6F5C&package=I10020160930");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
/*        new Thread() {
            @Override
            public void run() {
                long t = SystemClock.elapsedRealtime();
                List<SubCategoryListBean> artist = DataBaseHolder.getInstance().localRelativeDatabase.categoryDao().getAll();

                List<StyleNoListBean> allStyle = DataBaseHolder.getInstance().localRelativeDatabase.styleDao().getAll();

                List<SubCategoryListBean> brandList = new ArrayList<>(100);
                List<SubCategoryListBean> artistList = new ArrayList<>(100);
                List<SubCategoryListBean> bsList = new ArrayList<>(100);

                for (SubCategoryListBean bean : artist) {
                    if (TextUtils.equals(bean.category, "brand")) {
                        brandList.add(bean);
                    } else if (TextUtils.equals(bean.category, "artist")) {
                        artistList.add(bean);
                    } else if (TextUtils.equals(bean.category, "bs")) {
                        bsList.add(bean);
                    }
                }
                SparseArray<List<StyleNoListBean>> group = DataBaseHolder.getInstance().localRelativeDatabase.categoryDao().group(allStyle);
                group(group, brandList);
                group(group, artistList);
                group(group, bsList);

                for (SubCategoryListBean bean : bsList) {
                    if (bean.styleNoList == null) continue;
                }
                Log.d("tag", "db read spend " + (SystemClock.elapsedRealtime() - t) + " ms " + artistList.size() + "," + brandList.size() + "," + bsList.size()

                );
            }

            private void group(SparseArray<List<StyleNoListBean>> group, List<SubCategoryListBean> listBeans) {
                if (group != null && listBeans != null && !listBeans.isEmpty()) {
                    for (SubCategoryListBean bean : listBeans) {
                        List<StyleNoListBean> styleById = group.get(bean.id);
                        if (styleById == null || styleById.isEmpty()) continue;
                        List<StyleNoListBean> styleByCategory = new ArrayList<>(styleById.size());
                        for (StyleNoListBean styleBean : styleById) {
                            if (TextUtils.equals(styleBean.category, bean.category)) {
                                styleByCategory.add(styleBean);
                            } else {
                                Log.d("tag", "filter:" + bean.category + " BUT FIND " + styleBean.category);
                            }
                        }
                        bean.styleNoList = styleByCategory;
                    }
                }
            }
        }.start();*/
    }

    public void onOnBoardingClicked(View view) {
    }

    public void onTransformClicked(View view) {
    }


    class PriorityThread implements Runnable {
        int index;

        public PriorityThread(int index) {
            this.index = index;
        }

        @Override
        public void run() {
            Log.e("tag", "thread " + index + " start");
            try {
                Thread.sleep((long) (Math.random() * 10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            getHandler().post(() -> Toast.makeText(MainActivity.this, R.string.playerfragment_text, Toast.LENGTH_SHORT).show());
//            Log.e("tag", "-------thread " + index + " ends");
        }
    }


    LocationManager locationManager;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onMockLocationClicked(View view) {
        startActivity(new Intent(this, TranstraintActivity.class));
/*        if (locationManager == null) {
            locationManager =
                    (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                throw new IllegalArgumentException("ss");
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 1, locationListener);
        }

        mock();*/


    }

    public void mock() {
        try {
            double latitude = new Random().nextInt(180);
            Log.d(TAG, "mock run......." + latitude);
            // 模拟位置（addTestProvider成功的前提下）
            String providerStr = LocationManager.GPS_PROVIDER;
            Location mockLocation = new Location(providerStr);
            mockLocation.setLatitude(latitude);  // 维度（度）
            mockLocation.setLongitude(113); // 经度（度）
            mockLocation.setAltitude(30);  // 高程（米）
            mockLocation.setBearing(180);  // 方向（度）
            mockLocation.setSpeed(10);  //速度（米/秒）
            mockLocation.setAccuracy(0.1f);  // 精度（米）
            mockLocation.setTime(new Date().getTime());  // 本地时间
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
            }
            locationManager.setTestProviderLocation(providerStr, mockLocation);
        } catch (Exception e) {
            e.printStackTrace();
            // 防止用户在软件运行过程中关闭模拟位置或选择其他应用
//                stopMockLocation();
        }

    }

    private LocationListener locationListener = new LocationListener() {

        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            double lat = location.getLatitude();
            double lot = location.getLongitude();
            String str = "Latitude" + lat + "\r\nLongitude:" + lot;
            textView.setText(str);
            Log.i(TAG, "时间：" + location.getTime());
            Log.i(TAG, "经度：" + location.getLongitude());
            Log.i(TAG, "纬度：" + location.getLatitude());
            Log.i(TAG, "海拔：" + location.getAltitude());
        }

        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
                    Log.i(TAG, "当前GPS状态为可见状态");
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
                    Log.i(TAG, "当前GPS状态为服务区外状态");
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.i(TAG, "当前GPS状态为暂停服务状态");
                    break;
            }
        }

        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
        }

        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
        }
    };


    public static Map<String, SDKInfo> parseData(String jsonStr) {
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            if (jsonObject.optInt("code") != 0) return null;

            JSONObject dataObj = jsonObject.optJSONObject("data");
    /*        ControlInfo.DataBean bean = new ControlInfo.DataBean();
            bean.setConfigVersion(dataObj.optString("configVersion"));*/
            JSONObject sdkInfoObj = dataObj.optJSONObject("sdkInfo");
            HashMap<String, SDKInfo> sdkInfo = new HashMap<>(sdkInfoObj.length() * 2);
            for (Iterator<String> it = sdkInfoObj.keys(); it.hasNext(); ) {
                String key = it.next();
                String value = sdkInfoObj.getString(key);
                if (TextUtils.isEmpty(value)) continue;

                try {
                    JSONObject controlObj = new JSONObject(value);
                    SDKInfo info = new SDKInfo();
                    info.setState(controlObj.optInt("state"));

                    String extraString = controlObj.optString("extra");
                    if (!TextUtils.isEmpty(extraString)) {
                        info.setControlExtra(GsonAgent.getInstance().gson.fromJson(extraString, ControlExtra.class));
                    }

                    sdkInfo.put(key, info);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            return sdkInfo;
            /*bean.setSdkInfo(sdkInfo);
            return bean;*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final char[] charSet = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
    };
}
